import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus_ghz/pages/home/index.dart';
import 'package:flutter_enjoy_plus_ghz/pages/mine/index.dart';
import 'package:flutter_enjoy_plus_ghz/utils/Emitter.dart';
import 'package:flutter_enjoy_plus_ghz/utils/TokenManager.dart';

class TabsPage extends StatefulWidget {
  const TabsPage({Key? key}) : super(key: key);

  @override
  _TabsPageState createState() => _TabsPageState();
}

class _TabsPageState extends State<TabsPage> {
  List tabsList = [
    {
      'label': '首页',
      'icon': 'assets/tabs/home_default.png',
      'activeIcon': 'assets/tabs/home_active.png'
    },
    {
      'label': '我的',
      'icon': 'assets/tabs/my_default.png',
      'activeIcon': 'assets/tabs/my_active.png'
    }
  ];
  int activeIndex = 0;
  List<BottomNavigationBarItem> getTabBar() {
    List<BottomNavigationBarItem> list = [];
    for (var i = 0; i < tabsList.length; i++) {
      list.add(BottomNavigationBarItem(
        icon:
            Image.asset(tabsList[i]['icon'], width: 30, height: 30), // 未选中的图标,
        activeIcon: Image.asset(tabsList[i]['activeIcon'],
            width: 30, height: 30), // 选中的图标,
        label: tabsList[i]['label'], // 底部导航栏的文 字,
      ));
    }
    return list;
  }

  @override
  void initState() {
    super.initState(); // 初始化状态
    tokenManager.init(); // 初始化Token
    registerEventBus(); // 注册监听事件
  }

  registerEventBus() {
    eventBus.on<LogoutEvent>().listen((params) {
      // 退出登录
      Navigator.pushNamed(context, "/login");
    });
  }

  void updateIndex(int index) {
    setState(() {
      activeIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
        index: activeIndex,
        children: [
          const HomePage(),
          MinePage(
            currentIndex: activeIndex,
            updateIndex: updateIndex,
          )
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed, // 底部导航栏类型,
        currentIndex: activeIndex, // 当前选中的索引,
        selectedItemColor: const Color.fromARGB(255, 85, 145, 175),
        unselectedItemColor: Colors.black,
        items: getTabBar(),
        onTap: (int index) {
          setState(() {
            activeIndex = index;
          });
        },
      ),
    );
  }
}
